package com.weblog.weblogapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weblog.weblogapi.dao.mapper.ArticleMapper;
import com.weblog.weblogapi.dao.mapper.ArticleTagMapper;
import com.weblog.weblogapi.dao.pojo.*;
import com.weblog.weblogapi.service.ArticleService;
import com.weblog.weblogapi.service.ClassifyService;
import com.weblog.weblogapi.service.TagService;
import com.weblog.weblogapi.service.UserService;
import com.weblog.weblogapi.vo.ArticleVo;
import com.weblog.weblogapi.vo.Result;
import com.weblog.weblogapi.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private ClassifyService classifyService;
    private static long total=0;
    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page=new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getSortId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth(),
                pageParams.getFindMsg());
        List<Article> records = articleIPage.getRecords();
        total=articleIPage.getPages();
        return Result.success(copyList(records,true,true,false));
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCountView);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        List<Article> articles=articleMapper.selectList(queryWrapper);
        return Result.success(articles);
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        List<Article> articles=articleMapper.selectList(queryWrapper);
        return Result.success(articles);
    }

    @Override
    public Result findArticleById(int id) {
        Article article=articleMapper.selectById(id);
        //文章浏览量+1
        int articleView=article.getCountView()+1;
        article.setCountView(articleView);
        int i=articleMapper.updateById(article);
        return Result.success(copy(article,true,true,true,0));
    }

    @Override
    public Result publish(ArticleVo articleVo) {
        int i=0;
        articleVo.setCreateDate(sdf.format(new Date()));
        Article article=new Article();
        BeanUtils.copyProperties(articleVo,article);
        String title=article.getTitle();
        String content=article.getContent();
        int sort=article.getSortId();
        if((title==null||title.trim().equals(""))||(content==null||content.trim().equals(""))||sort==0){
            return Result.fail(444,"请补全相应信息");
        }
        else {
            i = articleMapper.insert(article);
            if(i==1) {
                int articleId = article.getId();
                List<Tag> tags = articleVo.getTags();
                if (tags.size() == 0) {
                    return Result.success("发布成功");
                }else {
                    for(int x=0;x<tags.size();x++){
                        ArticleTag articleTag=new ArticleTag();
                        articleTag.setArticleId(articleId);
                        articleTag.setTagId(tags.get(x).getId());
                        articleTagMapper.insert(articleTag);
                    }
                }
                    return Result.success("发布成功");
                }
            else {
                return Result.fail(440,"发布失败，请联系管理员");
            }
        }
    }

    @Override
    public Result deleteArticle(int id) {
        int i =articleMapper.deleteById(id);
        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ArticleTag::getArticleId,id);
        List<ArticleTag> articleTags=articleTagMapper.selectList(lambdaQueryWrapper);
        for(ArticleTag articleTag:articleTags){
            articleTagMapper.deleteById(articleTag.getId());
        }
        return Result.success(null);
    }

    @Override
    public Result updateArticle(ArticleVo articleVo) {
        Article oldArticle=articleMapper.selectById(articleVo.getId());
        String createDate=oldArticle.getCreateDate();
        int countView=oldArticle.getCountView();
        int countComment=oldArticle.getCountComment();
        Article article=new Article();
        BeanUtils.copyProperties(articleVo,article);
        article.setCountView(countView);
        article.setCountComment(countComment);
        article.setCreateDate(createDate);
        articleMapper.updateById(article);
        List<Tag> tags=articleVo.getTags();
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("article_id",oldArticle.getId());
        articleTagMapper.deleteByMap(map);
//        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper=new LambdaQueryWrapper();
//        lambdaQueryWrapper.eq(ArticleTag::getArticleId,oldArticle.getId());
//        articleTagMapper.delete(lambdaQueryWrapper);
//        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper=new LambdaQueryWrapper<ArticleTag>();
//        lambdaQueryWrapper.eq(ArticleTag::getArticleId,oldArticle.getId());
//        List<ArticleTag> articleTags=articleTagMapper.selectList(lambdaQueryWrapper);
//        for(ArticleTag articleTag:articleTags) {
//
//
//            articleTagMapper.deleteById(articleTag.getId());
//        }
        for(Tag tag:tags){

            ArticleTag articleTag=new ArticleTag();
            articleTag.setArticleId(oldArticle.getId());
            articleTag.setTagId(tag.getId());
            articleTagMapper.insert(articleTag);
            System.out.println(tag);
        }

        return Result.success(null);
    }

    @Override
    public Result findUserArticle(String id) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getUserId,id);
        queryWrapper.orderByDesc(Article::getCreateDate);
        List<Article> articles=articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles,true,true,false));
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor,  boolean isClassify) {
        List<ArticleVo> articleVoList=new ArrayList<>();
        for(Article record:records){
            articleVoList.add(copy(record,isTag,isAuthor,isClassify,total));
        }
        return articleVoList;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isClassify,long total){
        ArticleVo articleVo=new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);
        if(total!=0){
            articleVo.setTotal(total);
        }
        if(isTag){
            int articleId=article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if(isAuthor){
            String authorId=article.getUserId();
            User user=userService.findUserById(authorId);
            articleVo.setUsername(user.getUsername());
            articleVo.setAvatar(user.getAvatar());
        }

        if(isClassify){
            int sortId=article.getSortId();
            articleVo.setClassify(classifyService.findClassifyById(sortId));
        }
        return articleVo;
    }
}
